<?php

namespace app\modules\admin\controllers;

use app\common\services\StaticServices;
use app\models\IntegralGood;
use app\models\IntegralRecord;
use app\models\Member;
use app\models\MemberIntegral;
use app\models\Recommend;
use Yii;
use yii\base\Exception;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\Response;

class MemberController extends Controller {
  public function actionIndex()
  {
    $p = Yii::$app->request->get('p', 1);
    $mx_kw = trim(Yii::$app->request->get('mx_kw'));

    $user_info = Member::find()->where(['self_status' => 1]);

    if ($mx_kw) {
      $user_info->andWhere(['LIKE', 'member_name', $mx_kw]);

    }

    $page_size = StaticServices::$page;
    $total_count = $user_info->count();
    $total_page = ceil($total_count / $page_size);

    $list = $user_info->offset(($p - 1) * $page_size)->orderBy(['update_time' => SORT_DESC])->limit($page_size)->all();

    return $this->render('index', ['list' => $list, 'p' => $p, 'total_page' => $total_page]);
  }


  public function actionSet()
  {
    $member_id = intval(Yii::$app->request->get('id', 0));
    $member_info = [];
    if ($member_id) {
      $member_info = Member::find()->where(['id' => $member_id])->one();
    }
    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $member_name = trim(Yii::$app->request->post('member_name', ''));
        $member_phone = trim(Yii::$app->request->post('member_phone', ''));
        $member_address = trim(Yii::$app->request->post('member_address', ''));
        $member_id = intval(Yii::$app->request->post('member_id', 0));

        if (mb_strlen($member_name, 'utf-8') < 1) {
          throw new Exception('请填写会员姓名');
        }
        if (mb_strlen($member_phone, 'utf-8') != 11 && !preg_match('/^(0|86|17951)?(1[356789])[0-9]{9}$/', $member_phone)) {
          throw new Exception('请填写正确的手机号码');
        }
        if (mb_strlen($member_address, 'utf-8') < 1) {
          throw new Exception('请填写会员住址');
        }


        $member_arr = Member::find()->where(['id' => $member_id])->one();

        if ($member_arr) {
          $member_info = $member_arr;
        } else {
          $member = Member::find()->where(['member_phone' => $member_phone])->one();
          if ($member) {
            throw new Exception('此用户已经存在');
          }

          $member_info = new Member();
          $member_info->create_time = time();
        }

        $member_info->member_name = $member_name;
        $member_info->member_phone = $member_phone;
        $member_info->member_address = $member_address;
        $member_info->member_pwd = "00000";
        $member_info->update_time = time();
        $member_info->save(0);

        return ['code' => 200, 'msg' => '操作成功'];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
    return $this->render('set', ['info' => $member_info]);
  }


  public function actionGiveIntegral()
  {
    $member_id = intval(Yii::$app->request->get('id', 0));
    $member_info = [];
    if ($member_id) {
      $member_info = Member::find()->where(['id' => $member_id])->one();
    }

    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $member_id = intval(Yii::$app->request->post('member_id', 0));
        $integral_source = trim(Yii::$app->request->post('integral_source', ''));
        $integral = intval(Yii::$app->request->post('integral'));

        if (mb_strlen($integral_source, 'utf-8') < 1 && !StaticServices::checkIntegralSource($integral_source)) {
          throw new Exception("请选择积分来源");
        }
        $member_info = Member::find()->where(['id' => $member_id])->one();
        if (!$member_info) {
          throw new Exception("数据有误");
        }
        if ($integral_source == "其他" && $integral == 0) {
          throw new Exception("请填写给与的积分");
        }

        //保存给与积分的数据
        $member_integral = new MemberIntegral();
        $member_integral->member_id = $member_id;
        if ($integral_source != '其他') {
          $member_integral->integral = StaticServices::getIntegral()[$integral_source];
        } else {
          $member_integral->integral = $integral;
        }
        $member_integral->integral_source = $integral_source;
        $member_integral->update_time = time();
        $member_integral->create_time = time();
        if ($member_integral->save(0)) {
          //更新总积分
          $member_info->member_integral += $member_integral->integral;
          $member_info->update_time = time();
          $member_info->update(0);
        }

        return ['code' => 200, 'msg' => '积分给与成功'];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
    return $this->render('give', ['info' => $member_info]);
  }


  public function actionExchangeGoods()
  {
    $member_id = intval(Yii::$app->request->get("id", 0));
    $member_info = [];
    if ($member_id) {
      $member_info = Member::find()->where(["id" => $member_id])->one();
    }

    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $good_id = intval(Yii::$app->request->post('good_id', 0));
        $member_id = intval(Yii::$app->request->post('member_id', 0));

        if (!$good_id || !$member_id) {
          throw new Exception('参数有误');
        }

        $good_info = IntegralGood::find()->select(['good_integral', 'good_name'])->where(['id' => $good_id])->one();

        $member_info = Member::find()->where(['id' => $member_id])->one();

        if ($good_info->good_integral > $member_info->member_integral) {
          throw new Exception('用户积分不足');
        }

        $integral_record = new IntegralRecord();
        $integral_record->member_id = $member_id;
        $integral_record->good_id = $good_id;
        $integral_record->good_name = $good_info->good_name;
        $integral_record->good_integral = $good_info->good_integral;
        $integral_record->update_time = time();
        $integral_record->create_time = time();
        if ($integral_record->save(0)) {
          //兑换成功后，用户减掉相对应的积分
          $member_info->member_integral -= $good_info->good_integral;
          $member_info->update_time = time();
          $member_info->update(0);

          return ['code' => 200, 'msg' => "兑换成功"];
        }

      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }

    return $this->render('exchange', ['info' => $member_info]);
  }
}